from django.shortcuts import render_to_response
from django.http import HttpResponse
from models import Polygon
from django.core import serializers
from django.utils import simplejson
import re

def add_usda_plants_links(description):
    print 'making links'
    replace=r'<a href=http://plants.usda.gov/java/nameSearch?keywordquery=\1*+\2*&mode=sciname&submit>\1 \2</a>'
    match=r'([A-Z]{3})\s?([A-Z]{3})'
    res= re.sub(match,replace,description)
    return res

# Create your views here.
def post_handler(request):
    poly_id = request.POST['poly_id']
    park = request.POST['park']
    print park, poly_id
    
    try:
        polygon=Polygon.objects.get(new_id__iexact=poly_id, park__code__iexact=park)
        response_dict={}
        photos={}
        for photo in polygon.photo_set.all():
            photos[photo.direction]={'thumbnail':photo.thumbnail_image.url,'full':photo.original_image.url}
        
        response_dict['photos']=photos
        response_dict['polygon']={
            'new_id':polygon.new_id,
            'veg_notes':add_usda_plants_links(polygon.veg_notes),
            'soil_notes':add_usda_plants_links(polygon.soil_notes)
            }
        print response_dict
        
    except Polygon.MultipleObjectsReturned:
        response_dict={'polygon':{'veg_notes':'Multiple polygons found in database for that id.','soil_notes':'Multiple polgyons found in database for that id.'}}
        return HttpResponse(simplejson.dumps(response_dict), mimetype="application/javascript")

    except Polygon.DoesNotExist:
        response_dict={'polygon':{'veg_notes':'Polygon not found in database.','soil_notes':'Polygon not found in database.'}}
        return HttpResponse(simplejson.dumps(response_dict), mimetype="application/javascript")
    
    #data=serializers.serialize("json",list(polygon))
    #data={'polygon':data, 'photos':photos}
    
    #print response_dict
    
    return HttpResponse(simplejson.dumps(response_dict), mimetype="application/javascript")